<template>
  <div class="container">
    <div class="create-post-page">
      <h4>{{isEditMode? '编辑文章':"新建文章" }}</h4>
      <Uploader
        :uploaded="uploadedData"
        :beforeUpload="uploadCheck"
        @file-uploaded="handleFileUploaded"
        class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
      >
        <h2>点击上传头图</h2>
        <template #loading>
          <div class="d-flex">
            <div class="spinner-border text-secondary" role="status">
              <span class="visually-hidden">Loading...</span>
            </div>
            <h2>正在上传</h2>
          </div>
        </template>
        <template #uploaded="{ uploadedData }">
          <div class="uploaded-area">
            <img :src="uploadedData.data.url" />
            <h3>点击重新上传</h3>
          </div>
        </template>
      </Uploader>
      <h2>{{ titleVal }}</h2>
      <input type="file" name="file" @change="handleFileChange" />
      <validate-form @form-submit="onFormSubmit">
        <div class="mb-3">
          <label class="form-label">文章标题：</label>
          <ValidateInput
            :rules="titleRules"
            v-model="titleVal"
            placeholder="请输入文章标题"
            type="text"
          />
        </div>
        <div class="mb-3">
          <label class="form-label">文章详情：</label>
          <ValidateInput
            rows="10"
            tag="textarea"
            placeholder="请输入文章详情"
            :rules="contentRules"
            v-model="contentVal"
          />
        </div>
        <template #submit>
          <button class="btn btn-primary btn-large">提交</button>
        </template>
      </validate-form>
    </div>
  </div>
</template>

<script lang="ts">
import axios from 'axios'
import { useStore } from 'vuex'
import {
  GlobalDataProps,
  PostProps,
  ImageProps,
  Resptype
} from '../store/index'
import { defineComponent, ref, onMounted, watch } from 'vue'
import ValidateInput, { RulesProp } from '../components/ValidateInput.vue'
import ValidateForm from '../components/ValidateForm.vue'
import Uploader from '../components/UpLoader.vue'
import { useRouter, useRoute } from 'vue-router'
import createMessage from '../hooks/createMessage'
import { beforeUploadCheck } from '../helper'
export default defineComponent({
  components: {
    ValidateForm,
    Uploader,
    ValidateInput
  },
  setup() {
    const route = useRoute()
    const id = route.query.id
    const isEditMode = Boolean(route.query.id)
    const router = useRouter()
    const store = useStore()
    const titleVal = ref('')
    const uploadedData = ref()

    onMounted(() => {
      if (isEditMode) {
        store
          .dispatch('fetchPost', route.query.id)
          .then((rawData: Resptype<PostProps>) => {
            console.log(rawData.data)
            const currentPost = rawData.data
            if (currentPost.image) {
              uploadedData.value = { data: currentPost.image }
            }
            titleVal.value = currentPost.title
            contentVal.value = currentPost.content || ''
          })
      }
    })
    const titleRules: RulesProp = [
      { type: 'required', message: '文章标题不能为空' }
    ]
    const contentVal = ref('')
    const contentRules: RulesProp = [
      { type: 'required', message: '文章详情不能为空' }
    ]
    let imageId = ''

    const handleFileUploaded = (data) => {
      console.log(data)
      imageId = data.data._id
      createMessage(`上插图片id${data.data._id}`, 'success')
    }
    const uploadCheck = (file: File) => {
      const result = beforeUploadCheck(file, {
        format: ['image/jpeg', 'image/png'],
        size: 1
      })
      const { passed, error } = result
      if (error === 'format') {
        createMessage('上传图片只能是 JPG/PNG 格式!', 'error')
      }
      if (error === 'size') {
        createMessage('上传图片大小不能超过 1Mb', 'error')
      }
      return passed
    }
    const onFormSubmit = (result: boolean) => {
      if (result) {
        const { column, _id } = store.state.user
        const newPost: PostProps = {
          title: titleVal.value,
          content: contentVal.value,
          column,
          author: _id
        }
        if (imageId) {
          newPost.image = imageId
        }
        const actionName = isEditMode ? 'updatePost' : 'createPost'
        const postData = isEditMode
          ? {
              id: route.query.id,
              payload: newPost
            }
          : newPost
        store.dispatch(actionName, postData).then((res) => {
          console.log(res)
          // const token = store.state.token
          // axios.defaults.headers.common.Authorization = `Bearer ${token}`
          createMessage('发表成功，2秒后跳转到文章', 'success', 2000)

          router.push({ name: 'column', params: { id: column } })
        })
      }
    }
    const handleFileChange = (e: Event) => {
      console.log(e)
      const target = e.target as HTMLInputElement
      const files = target.files
      if (files) {
        const uploadFile = files[0]
        const formData = new FormData()
        formData.append(uploadFile.name, uploadFile)

        axios
          .post('/upload', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          })
          .then((res) => console.log(res))
      }
    }
    return {
      handleFileChange,
      titleRules,
      contentRules,
      contentVal,
      titleVal,
      onFormSubmit,
      handleFileUploaded,
      uploadCheck,
      isEditMode,
      uploadedData
    }
  }
})
</script>

<style lang="scss" scoped>
.file-upload-container {
  height: 200px;
  cursor: pointer;
  overflow: hidden;
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}
.uploaded-area {
  position: relative;
}
.uploaded-area:hover h3 {
  display: block;
}
.uploaded-area h3 {
  display: none;
  position: absolute;
  color: #999;
  text-align: center;
  width: 100%;
  top: 50%;
}
</style>
